package com.toplabs.unashu.listener;

import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.toplabs.unashu.common.Constants;
import com.toplabs.unashu.common.utils.RedisUtils;
import com.toplabs.unashu.vo.AuthTokenVO;
import org.springframework.stereotype.Component;

/**
 * @author toplabs
 * @since 2022/08/09
 * <p>This java file was created by toplabs in 2022/08/09.
 * The following is the description information about this file:</p>
 * <p>description: stp侦听器</p>
 */
@Component
public class StpListener implements SaTokenListener {

    private final RedisUtils redisUtils;

    public StpListener(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    /**
     * 每次登录时触发
     */
    @Override
    public void doLogin(String loginType, Object loginId, String tokenValue, SaLoginModel saLoginModel) {
        // login event
    }

    /**
     * 每次注销时触发
     */
    @Override
    public void doLogout(String loginType, Object loginId, String tokenValue) {
        deleteCache(tokenValue);
    }

    /**
     * 每次被踢下线时触发
     */
    @Override
    public void doKickout(String loginType, Object loginId, String tokenValue) {
        deleteCache(tokenValue);
    }

    /**
     * 每次被顶下线时触发
     */
    @Override
    public void doReplaced(String loginType, Object loginId, String tokenValue) {
        deleteCache(tokenValue);
    }

    /**
     * 每次被封禁时触发
     */
    @Override
    public void doDisable(String loginType, Object loginId, long disableTime) {
        StpUtil.logout();
    }

    /**
     * 每次被解封时触发
     */
    @Override
    public void doUntieDisable(String loginType, Object loginId) {
        // untie disable event
    }

    /**
     * 每次创建Session时触发
     */
    @Override
    public void doCreateSession(String id) {
        // create session event
    }

    /**
     * 每次注销Session时触发
     */
    @Override
    public void doLogoutSession(String id) {
        // logout session event
    }

    private void deleteCache(String tokenValue) {
        // 删除refresh_token相关信息
        if (redisUtils.hHasKey(Constants.CACHE_PREFIX_ACCESS_TOKEN, tokenValue)) {
            String tokenInfoStr = redisUtils.hGet(Constants.CACHE_PREFIX_ACCESS_TOKEN, tokenValue);
            AuthTokenVO tokenInfo = JSONUtil.toBean(tokenInfoStr, AuthTokenVO.class);
            String refreshToken = tokenInfo.getRefreshToken();
            redisUtils.hDel(Constants.CACHE_PREFIX_REFRESH_TOKEN, refreshToken);
            redisUtils.hDel(Constants.CACHE_PREFIX_ACCESS_TOKEN, tokenValue);
        }
    }
}
